package com.ailk.aee.pcc.server;

import com.ailk.aee.pcc.dao.UserSyncDao;
import com.ailk.aee.pcc.utils.CacheUtils;
import com.asiainfo.simplecache.SimpleCache;
import com.mongodb.DBObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;

/**
 * 用户同步服务
 *
 * @author pengzhang
 */
@Service
public class UserSyncServer {

    public static final String DEFAULT_VALUE = "000000";

    public static final String BATCH_COLUMN_NAME = "batchNum";

    private SimpleCache userSyncCache;

    private UserSyncDao userSyncDao;

    /**
     * 判断是否为相同指标同步
     *
     * @param userId   ?
     * @param batchNum ?
     *
     * @return ?
     */
    public boolean isSameBatchNum(String userId, String batchNum, String channelName) {
        String currentBatchNum = this.queryUserSyncColumnValue(userId, BATCH_COLUMN_NAME, true, channelName);

        //为空处理
        if (StringUtils.isEmpty(currentBatchNum)) {
            updateSyncByUserId(userId, BATCH_COLUMN_NAME, batchNum, channelName);
            return true;
        }

        return currentBatchNum.equalsIgnoreCase(batchNum);
    }

    public void updateSyncByUserId(String userId, String columnName, String columnValue, String channelName) {
        String columnCachekKey = CacheUtils.getUserSyncColumnCachekKey(userId, columnName, channelName);

        //当前值存入缓存中
        userSyncCache.put(columnCachekKey, columnValue);

        //当前值存入到mongo中
        userSyncDao.saveSyncColumnByUserId(userId, columnName, columnValue, channelName);
    }

    public String queryUserSyncColumnValue(String userId, String columnName, boolean saveToCache, String channelName) {

        String columnCacheKey = CacheUtils.getUserSyncColumnCachekKey(userId, columnName, channelName);
        Serializable value = userSyncCache.get(columnCacheKey);

        if (value == null) {
            //从mongo中获取
            DBObject object = userSyncDao.querySyncColumnByUserId(userId, columnName, channelName);
            boolean hasValue = object != null && object.get(BATCH_COLUMN_NAME) != null;
            String valueStr = hasValue ? (String) object.get(columnName) : DEFAULT_VALUE;

            if (saveToCache) {
                userSyncCache.put(columnCacheKey, valueStr);
            }
        }

        return (String) value;
    }
}
